package durst.action.account;

import java.io.StringReader;
import java.sql.SQLException;
import java.util.List;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;

import com.j256.ormlite.dao.Dao;

import durst.action.CalendarBasicAction;
import durst.data.Event;
import durst.data.UserCalendar;
import durst.data.dao.DaoFactory;
import durst.exception.AccessDeniedException;

public class EventDeleteActionBean extends CalendarBasicAction {
	@ValidateNestedProperties({ @Validate(field = "id") })
	private Event event;

	@ValidateNestedProperties({ @Validate(field = "id") })
	private List<Event> events;
	
	public Resolution handle() throws SQLException {
		DaoFactory.getInstance().createDao(Event.class).refresh(event);

		context.getRequest().setAttribute("event", event);

		if (event != null) {
			DaoFactory.getInstance().createDao(UserCalendar.class).refresh(event.getParent());

			if (!event.getParent().getOwner().equals(context.getAccount())) {
				throw new AccessDeniedException(false, context);
			}
			return new ForwardResolution("/account/eventdelete.jsp");
		}

		return cancel();
	}

	public Resolution confirm() throws SQLException {
		if (events != null) 
			for (Event event : events)
				deleteEvent(event);
		else if (event != null)
			deleteEvent(event);

		return cancel();
	}

	public Resolution cancel() {
		return new StreamingResolution("text/javascript", new StringReader(
				"Lightview.hide(); invoke($('hidden_form'), 'same');"));
	}

	@DefaultHandler
	public Resolution form() {
		context.getRequest().setAttribute("events", "true");
		return new ForwardResolution("/account/eventdelete.jsp");
	}
	
	private void deleteEvent(Event event) throws SQLException {
		Dao<Event, Integer> eventDao = DaoFactory.getInstance().createDao(Event.class);
		eventDao.refresh(event);
		
		if (event != null) {
			Dao<UserCalendar, Integer> calDao = DaoFactory.getInstance().createDao(
					UserCalendar.class);
			calDao.refresh(event.getParent());

			if (!event.getParent().getOwner().equals(context.getAccount())) {
				throw new AccessDeniedException(false, context);
			}
			
			eventDao.delete(event);
		}
	}
	
	public void setEvent(Event event) {
		this.event = event;
	}

	public Event getEvent() {
		return event;
	}

	public void setEvents(List<Event> events) {
		this.events = events;
	}

	public List<Event> getEvents() {
		return events;
	}
}
